﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.LogicalGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.LogicalGrid
{
    public class UpdateLogicalGridHandler : IRequestHandler<UpdateLogicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogicalGridModel> logicalRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateLogicalGridHandler> logger;

        public UpdateLogicalGridHandler(IBaseRepository<LogicalGridModel> logicalRepo,IMapper mapper ,ILogger<UpdateLogicalGridHandler> logger)
        {
            this.logicalRepo = logicalRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateLogicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();//实例化响应包装类

            //判断名称和编码唯一
            var logicalGrid = logicalRepo.GetAll().Where(x=>(x.GridName==request.GridName||x.GridCode==request.GridCode)&&x.Id!=request.Id).FirstOrDefault();

            if (logicalGrid != null) {
                res.Msg = "网格名称或编码已经存在!";
                res.Code = ApiEnum.Failed;
                return res;//不要忘了返回
            }

            var model =  await logicalRepo.GetModel(request.Id);//这里是不是有一个id= request.Id
            if (model == null) {
                res.Msg = "您要修改的逻辑网格不存在!";
                res.Code = ApiEnum.Failed;
                return res;//不要忘了返回
            }

            //把request 转为Model
            //model  = mapper.Map<LogicalGridModel>(request);//又有一个实体 id也是request.Id
            model = mapper.Map(request,model);

            int r = await logicalRepo.UpdateAsync(model);
            if (r > 0)
            {
                res.Msg = "更新逻辑网格成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "更新逻辑网格失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;


        }
    }
}
